
#include <adm.h>

typedef struct AdminNode {
	int fd;
	struct AdminNode *next;
	struct AdminNode *prev;
} AdminNode;

typedef struct AdminQueue {
	rp_mutex_t mutex;
	rp_sem_t sem;
	int qlength;
	AdminNode *head;
	AdminNode *tail;
} AdminQueue;

Err rp_admq_init(AdminQueue *queue)
{
	char fname[] = "rp_admq_init";
	char msg[] = "fatal error";
	Err err;
	FLOG_IN(fname);

	err = rp_mutex_init(&(admq->mutex));
	err = rp_sem_init(&(admq->sem), 0, 0);
	admq->head = NULL;
	admq->tail = NULL;

	FLOG_OUT(fname);
	return err;
}

Err rp_admq_finalize(AdminQueue *queue)
{
        char fname[] = "rp_admq_finalize";
        char msg[] = "fatal error";
        Err err;
        AdminNode *node;

        if (!admq->qlength)   return err;                     // The queue has NOT been initialized

        err = rp_mutex_lock(&(admq->mutex));
        if (!admq->qlength)
        {
                rp_log(LOG_DEBUG, fname, "The admin queue has NOT been initialized");
                err = rp_mutex_unlock(&(admq->mutex));
                return err;
        }
        if (!tqueue->ntask)
        {
                rp_log(LOG_DEBUG, fname, "The task queue is empty");
                err = rp_mutex_unlock(&(tqueue->mutex));
                return err;
        }

        tnode = tqueue->tail;
        while (tnode->prev)
        {
                tnode = tnode->prev;
                free(tnode->next);
        }
        free(tnode);

        tqueue->head = NULL;
        tqueue->tail = NULL;
        tqueue->qlength = 0;
        tqueue->ntask = 0;

        err = rp_mutex_unlock(&(tqueue->mutex));

        return err;
}

Err rp_admq_put(AdminQueue *queue, int fd);
int  *rp_admq_get(AdminQueue *queue);

void rp_rindexd_adm(int fd, short event, void *arg)
{
	static char fname[] = "rp_rindexd_adm";
	static char msg[] = "fatal message";
	Err err;
	static int clifd;
	static struct sockaddr_in cliaddr;
	static socklen_t clilength;
	FLOG_IN(fname);

	memset(&cliaddr, 0, sizeof(struct sockaddr_in));
	clilength = 0;
	/*	accept the tcp connection   */
	if (!(clifd = rp_comm_accept(fd, &cliaddr, &clilength)))	
	{
		rp_log(LOG_ERROR, fname, "No command connection is setup.");
		return;
	}

	err = rp_admq_put(&global.admq, clifd);
	err = rp_sem_post(&global.admq.sem);

	FLOG_OUT(fname);
}




